package glin

import (
	"os"
	"time"

	"gitee.com/zhangycsz/glin/gommon/glog"
)

type LogFile struct {
	FileName string //日期
	Prefix   string //文件名称前置
	Path     string //日志文件夹路径
	Fb       *os.File
}

func (ths *LogFile) Create() (err error) {
	if !CheckExists(ths.Path) {
		MkdirAll(ths.Path)
	}
	var file *os.File
	fileName := time.Now().Format("2006-01-02") + "_" + ths.Prefix + ".log"
	ths.FileName = fileName
	filePath := ths.Path + "/" + fileName
	if CheckExists(filePath) {
		file, err = os.OpenFile(filePath, os.O_APPEND|os.O_RDWR, 0644)
	} else {
		file, err = os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	}
	ths.Fb = file
	return
}

func (ths *LogFile) Write(p []byte) (n int, err error) {
	fileName := time.Now().Format("2006-01-02") + "_" + ths.Prefix + ".log"
	if fileName != ths.FileName {
		ths.Close()
		err = ths.Create()
		if err != nil {
			panic(err)
		}
	}
	n, err = ths.Fb.WriteString(string(p))
	return
}

func (ths *LogFile) Close() {
	if ths.Fb != nil {
		ths.Fb.Close()
	}
}

// 全局的默认的日志
var GLog *glog.Logger

// 创建日志对象，其中prefix文件后缀
func NewLog(prefix string) *glog.Logger {
	l := glog.New(prefix)
	conf := NewDefaultConfig()
	logFile := &LogFile{Prefix: prefix, Path: conf.LogPathDir}
	err := logFile.Create()
	if err != nil {
		panic(err)
	}
	l.SetOutput(logFile)
	return l
}
